import { Component, OnInit } from '@angular/core';

/**
 * @title One Year Calendar
 */
@Component({
  templateUrl: './calendar-lite-year.component.html',
  styleUrls: ['./calendar-lite-year.component.css'],
})
export class CalendarLiteYearComponent implements OnInit {

  months = Array.from(Array(12).keys());

  currentYear = new Date().getFullYear();

  years = Array.from(Array(30).keys()).map((offset) => this.currentYear - offset);

  days: Date[] = [];

  constructor() { }

  ngOnInit() {
    this.days = this.buildDays();
  }

  toggleSelectAll() {
    const allDays = this.buildDays();
    if (allDays.length > this.days.length) {
      this.days = allDays;
    } else {
      this.days = [];
    }
  }

  onlyWeekend() {
    this.days = this.buildDays();
    this.days = this.days.filter((day) => {
      const dayOfWeek = day.getDay();
      return dayOfWeek === 0 || dayOfWeek === 6;
    });
  }

  onlyWeekday() {
    this.days = this.buildDays();
    this.days = this.days.filter((day) => {
      const dayOfWeek = day.getDay();
      return dayOfWeek !== 0 && dayOfWeek !== 6;
    });
  }

  onYearChange() {
    this.days = this.buildDays();
  }

  onDayChange(day) {
    const date = day.date;
    const dayIndex = this.days.findIndex((_day) => this.sameDay(_day, date));
    if (dayIndex > -1) {
      this.days.splice(dayIndex, 1);
    } else {
      this.days.push(date);
    }
    this.days = [...this.days];
  }

  private buildDays() {
    let currentDay = new Date(this.currentYear, 0, 1);
    const lastDay = new Date(this.currentYear, 11, 31);

    const days = [];
    while (!this.sameDay(currentDay, lastDay)) {
      days.push(new Date(currentDay));
      const nextDay = new Date(currentDay);
      nextDay.setDate(nextDay.getDate() + 1);
      currentDay = nextDay;
    }
    days.push(lastDay);

    return days;
  }

  private sameDay(d1: Date, d2: Date) {
    return d1.getFullYear() === d2.getFullYear() &&
      d1.getMonth() === d2.getMonth() &&
      d1.getDate() === d2.getDate();
  }
}
